package net.hky365.lowcode.magic.function;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.hky365.shop.framework.common.enums.DocumentEnum;
import net.hky365.shop.framework.security.core.LoginUser;
import net.hky365.shop.framework.security.core.util.SecurityFrameworkUtils;
import net.hky365.shop.framework.tenant.core.context.TenantContextHolder;
import net.hky365.shop.module.system.api.tenant.TenantInfoApi;
import net.hky365.shop.module.system.api.tenant.dto.TenantDTO;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
import org.ssssssss.magicapi.core.config.MagicFunction;
import org.ssssssss.script.annotation.Comment;
import org.ssssssss.script.annotation.Function;

import java.util.Collection;
import java.util.Map;
import java.util.Optional;

/**
 * 租户函数集合
 *
 * @author hl-king
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class MagicFunctions implements MagicFunction, InitializingBean {
    private final TenantInfoApi tenantInfoApi;

    @Function
    @Comment("忽略租户")
    public void tenantIgnore(boolean ignore) {
        TenantContextHolder.setIgnore(ignore);
    }

    @Function
    @Comment("获取当前登录人信息")
    public LoginUser currentUser() {
        return SecurityFrameworkUtils.getLoginUser();
    }

    @Function
    @Comment("获取租户id")
    public long currentRequiredTenantId() {
        return TenantContextHolder.getRequiredTenantId();
    }

    @Function
    @Comment("获取租户id")
    public long currentTenantId() {
        return TenantContextHolder.getTenantId();
    }

    @Function
    @Comment("获取当前租户")
    public TenantDTO currentRequiredTenant() {
        return Optional
                .ofNullable(tenantInfoApi.getTenant(TenantContextHolder.getRequiredTenantId()))
                .orElseThrow(() -> new NullPointerException("TenantContextHolder 不存在租户编号！可参考文档：" + DocumentEnum.TENANT.getUrl()));
    }

    @Function
    @Comment("获取当前租户")
    public TenantDTO currentTenant() {
        return Optional
                .ofNullable(TenantContextHolder.getTenantId())
                .map(tenantInfoApi::getTenant)
                .orElse(null);
    }

    @Function
    @Comment("获取当前租户")
    public TenantDTO getTenant(Long id) {
        return Optional
                .ofNullable(id)
                .map(tenantInfoApi::getTenant)
                .orElse(null);
    }

    @Function
    @Comment("获取当前租户")
    public Map<Long, TenantDTO> getTenants(Collection<Long> ids) {
        return tenantInfoApi.getTenants(ids);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        log.info("注册自定义函数");
    }
}
